package org.jeecg.modules.driver;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.util.ByteUtils;

@Slf4j
public class DriverPortocal1_0_MsgToByteEncoder extends MessageToByteEncoder<String> {  //1

    public final byte[] fixHead = {(byte)0xAA, (byte)0x55};
//    public final byte[] fixTail = {(byte)0x55, (byte)0xAA};

    @Override
    public void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        byte[] data = msg.getBytes(DriverPortocal1_0.ENCODING);
        int length = data.length + 1; //With CRC byte
        byte[] merge = ByteUtils.byteMerger(fixHead,new byte[]{(byte)length});
        merge = ByteUtils.byteMerger(merge,data);
        merge = ByteUtils.byteMerger(merge,new byte[]{(byte)ByteUtils.getXor(data)});
//        merge = ByteUtils.byteMerger(merge,fixTail);
        out.writeBytes(merge); //Header
        log.info("已发送 " +  ByteUtils.toHexStringDisplay(merge));
    }

}
